<template>
  <div>
    <div class="write-btn">
      <el-button type="primary" @click="sumbit">
        提交
      </el-button>
    </div>
    <el-row>
      <el-col :span="12">
        <!-- markdown编辑器的基本操作 -->
        <textarea
          ref="editor"
          class="md-editor"
          :value="content"
          cols="30"
          rows="10"
          @input="update"
        />
      </el-col>
      <el-col :span="12">
        <div class="mardown-body" v-html="compiledContent"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import marked from 'marked'
import hljs from 'highlight.js'
import javascript from 'highlight.js/lib/languages/javascript' // js代码高亮问题
import 'highlight.js/styles/monokai-sublime.css'
export default {
  data () {
    return {
      content: `# 开课吧
* 上课
* 吃饭
* 写代码

\`\`\`javascript

  let a =1;
  console.log(a)
\`\`\`
      `
    }
  },
  computed: {
    compiledContent () {
      return marked(this.content, {})
    }
  },
  mounted () {
    this.timer = null // 不需要响应式、避免性能损耗
    this.bindEvents()
    marked.setOptions({
      rendered: new marked.Renderer(),
      highlight (code) {
        return hljs.highlightAuto(code).value
      }
    })
  },
  methods: {
    bindEvents () {
      // 复制上传
      this.$refs.editor.addEventListener('paste', (e) => {
        const files = e.clipboardData.files
        // 直接上传 参考 uc.vue
        console.log(files)
      })
      // 拖拽上传
      this.$refs.editor.addEventListener('drop', (e) => {
        const files = e.dataTransfer.files
        // 直接上传 参考 uc.vue
        console.log(files)
        e.preventDefault()
      })
    },
    update (e) {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.content = e.target.value
      }, 350)
    },
    async sumbit () {
      // 文章列表 点赞 关注 草稿
      // user =》 article 一对多
      const ret = await this.$http.post('/article/create', {
        content: this.content, //  selected:false
        compiledContent: this.compiledContent // 显示只读取这个
      })
      if (ret.code === 0) {
        this.$notify({
          title: '创建成功',
          type: 'success',
          message: `文章《${ret.data.title}》创建成功`
        })
        setTimeout(() => {
          // this.$router.push({ path: '/article/' + ret.data.id })
          this.$router.push({ path: '/' })
        })
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  .md-editor
    width 95%
    height 100vh
    outline none
  .write-btn
    position fixed
    z-index 100
    right 30px
    top 10px
</style>
